<template>
  <div v-if="isGetData">
    <Template1
      :time="time"
      :product="productInfo"
      :sku-info="computeSku"
      :hasProvince="hasProvince"
      @execute="handleBtnClick"
      :original-sku="skuInfo"
      :areaInfo="areaInfo"
      :provinceList="provinceList"
      :logisticsList="logisticsList"
      :storeList="storeList"
      :globalConfig="config"
      :remoteList="remoteList"
      :instruction="instructionInfo"
      :policy-list="policyList"
      :orderInfo="orderInfo"
      :showSuccess="showSuccess"
      :showOrder="showOrder"
      :comment-avg-score="commentAvgScore"
      :comment-list="commentList"
      :rollList="rollList"
      :recommend-list="recommendList"
      v-if="productInfo.templateProperty === '123'"
    />
    <Template2
      :product="productInfo"
      :sku-info="computeSku"
      :hasProvince="hasProvince"
      @execute="handleBtnClick"
      :original-sku="skuInfo"
      :areaInfo="areaInfo"
      :provinceList="provinceList"
      :logisticsList="logisticsList"
      :storeList="storeList"
      :globalConfig="config"
      :remoteList="remoteList"
      :policy-list="policyList"
      v-if="productInfo.templateProperty === 'template2'"
    />
    <Template4
      :product="productInfo"
      :sku-info="computeSku"
      :hasProvince="hasProvince"
      :custDown="time"
      @execute="handleBtnClick"
      :original-sku="skuInfo"
      :areaInfo="areaInfo"
      :provinceList="provinceList"
      :logisticsList="logisticsList"
      :storeList="storeList"
      :globalConfig="config"
      :remoteList="remoteList"
      :policy-list="policyList"
      :instruction="instructionInfo"
      v-if="productInfo.templateProperty === 'template4'"
      :showSuccess="showSuccess"
      :showOrder="showOrder"
      :orderInfo="orderInfo"
      :rollList="rollList"
      :comment-list="commentList"
      :comment-avg-score="commentAvgScore"
    />
    <Template3
      :product="productInfo"
      :sku-info="computeSku"
      :hasProvince="hasProvince"
      @execute="handleBtnClick"
      :original-sku="skuInfo"
      :areaInfo="areaInfo"
      :provinceList="provinceList"
      :logisticsList="logisticsList"
      :custDown="time"
      :storeList="storeList"
      :globalConfig="config"
      :package-list="packageList"
      :comment-list="commentList"
      :recommend-list="recommendList"
      :comment-avg-score="commentAvgScore"
      :policy-list="policyList"
      :remoteList="remoteList"
      :instruction="instructionInfo"
      v-if="productInfo.templateProperty === 'template3'"
      :showSuccess="showSuccess"
      :showOrder="showOrder"
      :orderInfo="orderInfo"
      :rollList="rollList"
    />


    <div class="icons fixed bottom-[50PX] right-[20PX]" style="z-index: 999999;">
      <div v-for="(item,index) in computeIcons" :key="index"
           class="bg w-[28PX] h-[28PX] mb-[20PX] cursor-pointer"
           :style="`background-image:url(${item.url })`"
           @click="handleBtnClick({type:item.code})"
      >


      </div>
    </div>

  </div>
</template>
<script lang="ts" setup>
import Template1 from './template/template1.vue'
import Template2 from './template/template2.vue'
import Template3 from './template/template3/index.vue'
import Template4 from './template/template4/index.vue'

import {getLanguage} from "@/utils/langue";
import {useRoute} from 'vue-router'
import {
  getProductDetail,
  getProductSku,
  getAreaById,
  submitOrder,
  getStoreList,
  getLogistics,
  getConfig,
  getAreaListByLogisticsId,
  getPackage,
  getComment,
  getRecommend,
  getPolicy, getAreaList1, getRemoteArea, getInstruction, spm
} from '@/api/h5'
import {ProductDetailRespVO, ProductSpecsValueDO, GlobeStateRespVO} from '@/api/h5/type'
import {useAppStore} from '@/store/modules/app'
import {deepCopy, throttle, deviceType, spmFaceBook} from '@/utils'
import {useMessage} from '@/hooks/web/useMessage'
import {getProductRoll} from '@/api/mall/product/roll'

const message = useMessage()

const productInfo = ref<ProductDetailRespVO>({})

const skuInfo = ref<ProductSpecsValueDO[]>([])
const packageList = ref([])
const commentList = ref([])
const recommendList = ref([])
const commentAvgScore = ref(0)
const pId = ref('')

const areaInfo = ref<GlobeStateRespVO>({})

const hasProvince = ref(true)

const showSuccess = ref(false)
const showOrder = ref(false)

const orderInfo = ref({
  orderId: '',
})

const provinceList = ref([])
const servicePolicyId = ref()
const websiteId = ref()
const logisticsList = ref([])
const policyList = ref([])
const isGetData = ref(false)

const remoteList = ref([]);

const storeList = ref([])

const rollList = ref()

const adId = ref('')

const config = ref({
  orderDelectSteat: 1 //提交之后是否清除表单信息
})


const instructionInfo = ref({})

const icons = ref([
  {
    url: "https://img.alicdn.com/imgextra/i4/801089336/O1CN01ir2eaC2IpwkdPodzJ_!!801089336.png",
    code: "top",
  },
  {
    url: "https://img.alicdn.com/imgextra/i2/801089336/O1CN01RC02Zp2IpwkWxF6HT_!!801089336.png",
    code: "whatsappContact"
  },
  {
    url: "https://img.alicdn.com/imgextra/i4/801089336/O1CN01LXkyrG2IpwkbpLGaw_!!801089336.png",
    code: "lineContact"
  },
  {
    url: "https://img.alicdn.com/imgextra/i1/801089336/O1CN01NedPMP2IpwkckPenw_!!801089336.png",
    code: "facebookContact"
  },
  {
    url: "https://img.alicdn.com/imgextra/i1/801089336/O1CN01uE9nic2IpwkcT5uqg_!!801089336.png",
    code: "messengerContact"
  },
  {
    url: "https://img.alicdn.com/imgextra/i3/801089336/O1CN01yZcOH62IpwkdpXI5Y_!!801089336.png",
    code: "instagramContact"
  },
  {
    url: "https://img.alicdn.com/imgextra/i1/801089336/O1CN019gr7lZ2IpwkWxDxaX_!!801089336.png",
    code: "email"
  },
  {
    url: "https://img.alicdn.com/imgextra/i3/801089336/O1CN01crhqlx2IpwkdKWPX0_!!801089336.png",
    code: "phone"
  },
  {
    url: "https://img.alicdn.com/imgextra/i3/801089336/O1CN01xccQiE2IpwkfZ1XwB_!!801089336.png",
    code: "order"
  }
])

const computeIcons = computed(() => {
  let list = icons.value || [];
  return list.filter(item => {
    if (item.code == "top" || item.code == "order") {
      return true
    } else {
      return productInfo.value[item.code]
    }
  })
})

const time = ref({hours: 0, minutes: 0, seconds: 0});
const countdownActive = ref(false);
let timer: NodeJS.Timeout | null = null;

const computeSku = computed(() => {
  try {
    let list = deepCopy(skuInfo.value)
    if (list.length > 0) {
      let arr = []

      let sizeArr = list[0].name.split(/§/gi)

      let sizeFoeignArr = list[0].nameForeign.split(/§/gi)
      sizeArr.forEach((item, index) => {
        //找到 不重复的 属性
        let obj = {
          name: item,
          nameForeign: sizeFoeignArr[index],
          list: []
        }
        list.forEach((it) => {
          let propertyArr = it?.propertyValue.split(/§/gi)
          let propertyValueForeignArr = it?.propertyValueForeign.split(/§/gi)
          let imgArr = it?.picture.split(/,/gi)
          let isIn = obj.list.find((at) => {
            return at.name == propertyArr[index]
          })
          if (!isIn) {
            obj.list.push({
              name: propertyArr[index],
              nameForeign: propertyValueForeignArr[index],
              url: (imgArr && imgArr.length > 0 && imgArr[index]) || ''
            })
          }
        })

        arr.push(obj)
      })
      if (arr.length == 1) {
        arr[0].selected = 1
      }
      return arr
    } else {
      return []
    }
  } catch (e) {
    console.log(e)
  }
})

const initPage = async () => {
  let url = window.location.href

  let urlStr = url.split('#')[0]
  let paramsStr = urlStr.split('?')[1]
  if (paramsStr) {
    let paramsArr = paramsStr.split('&')
    let params = {}
    paramsArr.forEach((item) => {
      let keyVal = item.split('=')
      params[keyVal[0]] = keyVal[1]
    })
    if (params.utm_term) {
      adId.value = params.utm_term
    }
  }

  let productId = useRoute().query.id

  let tenantId = useRoute().query.tenantId
  pId.value = productId
  useAppStore().setTenantId(tenantId);

  let productCallback = await getProductDetail({
    id: productId,
    browserLanguage: navigator.language || navigator.userLanguage,
    deviceType: deviceType()
  })

  isGetData.value = true;

  let skuCallback = await getProductSku({productId: productId});

  //如果不是套餐商品   组装成套餐商品
  if (productCallback.thaliFlag != 1) {
    productCallback.thalis = [
      {
        discountedPrice: productCallback.discountedPrice,
        id: (+new Date()).toString(),
        name: "",
        nameForeign: "",
        originalPrice: productCallback.originalPrice,
        saleFlag: 1,
        shippingFee: productCallback.shippingFee,
        thaliDetailList: [
          {
            cover: productCallback.cover,
            id: (+new Date()).toString(),
            independenceFlag: 0,
            number: 1,
            productId: productCallback.id,
            productName: productCallback.titleExternal,
            specs: skuCallback
          }
        ]
      }
    ]
  }

  productCallback.thalis.forEach(item => {
    item.thaliDetailList.forEach(it => {
      it.specs.forEach(at => {
        at.product = deepCopy(it)
      })
    })
  })


  let callback = await Promise.all([
    getPackage({id: productId}),
    getComment({productId: productId, pageNo: 1, pageSize: 50}),
    getRecommend({id: productId}),

  ])
  //商品详情
  productInfo.value = productCallback;

  //滾動購買
  if (productInfo.value.rollId) {
    const rollListRes = await getProductRoll(productInfo.value.rollId)
    console.log(rollListRes)
    rollList.value = rollListRes || []
  }


  pId.value = productInfo.value.id;

  document.title = productInfo.value.titleExternal

  if (productInfo.value.countdown && productInfo.value.countdown > 0) {
    // 启动倒计时示例
    startCountdown(productInfo.value.countdown); // 启动1小时倒计时
  }

  servicePolicyId.value = productInfo.value.bottomPolicy
  websiteId.value = productInfo.value.websiteId
  if (productInfo.value.bottomPolicy) {
    // 获取政策
    getPolicy({servicePolicyId: servicePolicyId.value, websiteId: websiteId.value}).then((res) => {
      policyList.value = res
    })
  }

  //获取sku
  skuInfo.value = skuCallback

  //获取套餐
  packageList.value = callback[0]
  // 获取评论
  commentList.value = callback[1].list

  //滾動購買
  if (productInfo.value.rollId) {
    const rollListRes = await getProductRoll(productInfo.value.rollId)
    rollList.value = rollListRes || {}
    // 如果滾動購買方式为2,需要追加到commentList中
    if (rollList.value?.style == '2' && rollList.value?.commentList.length > 0) {
      let totalScrore = 0;
      let temp = rollList.value.commentList?.map((item) => {
        let score = Math.round(Math.random() * 1) + 4;
        totalScrore += score;
        return {
          userId: 0,
          userNickname: item.userName,
          userAvatar: item.userAvatar,
          scores: score,
          content: item.content,
          commentTime: item.createTime,
          picUrls: [],
          visible: true,
        }
      })
      if (commentList.value.length === 0) {
        commentAvgScore.value = Number(Number(totalScrore / temp.length).toFixed(1))
      }
      commentList.value = commentList.value.concat(temp)
    }
  }
  if (callback[1].avgScore) {
    commentAvgScore.value = callback[1].avgScore
  }

  // 获取推荐商品
  recommendList.value = callback[2].recommendRespList
  // 获取政策


  await initPromise()
}

const initPromise = async () => {
  let res = await Promise.all([
    getAreaById({
      id: productInfo.value?.areaId
    }),
    getLogistics({
      //物流方式
      id: productInfo.value?.areaId
    }),
    getConfig(),

    getRemoteArea({
      stateId: productInfo.value?.areaId
    }),
    getInstruction({
      stateId: productInfo.value?.areaId
    })
  ])


  //地區信息 globeStateDetailList為null时,不需要显示省市区,只需要显示详细地址
  areaInfo.value = res[0]

  logisticsList.value = (res[1] || []).filter(item => {
    let logisticsMethod = productInfo.value.logisticsMethod?.split(',') || [];
    let it = logisticsMethod.find(at => {
      return at == item.id
    })
    return !!it
  });

  let method = logisticsList.value[0]

  await getAreaList(method)


  let configList = res[2]
  if (configList && configList.length > 0) {
    config.value = configList[0]
  }

  //获取偏远地区列表
  remoteList.value = res[3]?.list || []

  console.log(res[4])
  instructionInfo.value = res[4];

  console.log(instructionInfo)


  //初始化facebook埋点
  initFacebook();

  //访问埋点
  spm({
    productId: pId.value,
    siteDomain: window.location.hostname,// "shop.dashubobo.com",//window.location.hostname,
    productName: productInfo.value.title || '',
    action: 1,
    pageType: 1,
    accessAddress: window.location.href,
    productType: productInfo.value.type,
    actionDetail: `访问商品${productInfo.value.title}`
  })


  isGetData.value = true
}

const initFacebook = () => {
  return
  if (productInfo.value.facebook) {
    fbq('init', productInfo.value.facebook);

    setTimeout(() => {
      spmFaceBook({
        code: "ViewContent",
        attachData: {
          content_name: productInfo.value.titleExternal,
          content_category: productInfo.value.categoryName || '',
          content_ids: [pId.value],
          content_type: 'product',
          value: productInfo.value.discountedPrice,
          currency: areaInfo.value.currency
        }
      }, productInfo.value)
    }, 1000)
  }

}


const getAddress = () => {

}


/**
 * 獲取 地區列表
 * */
const getAreaList = async (method) => {
  if (method) {

    let res;
    if (method.directlyStatus == 0) {
      res = await getAreaList1({
        methodId: method.id,
        stateId: method.stateId,
        pageSize: 1000
      })
    } else {
      res = await getAreaListByLogisticsId({
        methodId: method.id,
        pageSize: 1000
      })
    }
    if (!res?.list?.length) {
      provinceList.value = []
      hasProvince.value = false
    } else {
      hasProvince.value = true
      provinceList.value = generateProvince(deepCopy(res.list))
    }

  }
}

/**
 * 生成省市区树
 * */
const generateProvince = (provinceData) => {
  let cityList = []
  provinceData.forEach((item) => {
    let isIn = cityList.find((at) => {
      return item.province == at.name
    })
    if (!isIn) {
      cityList.push({
        name: item.province,
        list: []
      })
    }
  })

  cityList.forEach((item) => {
    let lis = provinceData.filter((it) => {
      return it.province == item.name
    })
    item.list = (lis || []).map((item) => {
      return {
        name: item.city,
        id: item.id,
        list: []
      }
    })

    // item.list.forEach((at) => {
    //   let lisArea = provinceData.filter((it) => {
    //     return it.city == at.name
    //   })

    //   at.list = (lisArea || []).map((z) => {
    //     return {
    //       name: z.area,
    //       id: z.id
    //     }
    //   })
    // })
  })

  return cityList
}

const handleBtnClick = (e) => {
  let type = e.type
  try {
    fn[type](e)
  } catch (e) {
    console.log(e)
    console.log(`${type}不存在`)
  }
}


const startCountdown = (hours: number) => {

  const totalSeconds = Math.floor(hours * 3600);
  time.value.hours = Math.floor(totalSeconds / 3600);
  time.value.minutes = Math.floor((totalSeconds % 3600) / 60);
  time.value.seconds = totalSeconds % 60;
  countdownActive.value = true;

  clearInterval(timer);
  timer = setInterval(() => {
    if (time.value.seconds > 0) {
      time.value.seconds--;
    } else if (time.value.minutes > 0) {
      time.value.minutes--;
      time.value.seconds = 59;
    } else if (time.value.hours > 0) {
      time.value.hours--;
      time.value.minutes = 59;
      time.value.seconds = 59;
    } else {
      // 倒计时结束，重新开始
      startCountdown(hours); // 重新开始倒计时
    }
  }, 1000);
}

const stopCountdown = () => {
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
  countdownActive.value = false;
}

// 在组件销毁前停止计时器
onUnmounted(() => {
  stopCountdown();
});

let isClick = false;

const fn = {
  order() {
    showOrder.value = true
  },
  showOrder() {
    showOrder.value = true
  },
  async store({data, callback}) {
    //
    let res = await getStoreList({
      name: data.regionName,
      methodId: logisticsList.value[data.activeLogistics].id
    })
    let list = res.map(item => {
      return {
        ...item,
        storeName: `${item.storeName}-${item.detailedAddress}`,
        detailedAddress: `${item.detailedAddress}-${item.storeName}-${item.storeNumber}`
      }
    })
    storeList.value = list
    callback && callback(list)
  },
  confirm: async (e) => {
    if (isClick) {
      return
    }
    isClick = true;
    try {
      let option = {
        areaId: productInfo.value.areaId,
        ...e.form,
        address: e.address,
        orderAmount: e.priceInfo.discountPrice,
        orderLink: window.location.href,
        orderNumber: e.form.number,
        status: 1,
        utmTerm: adId.value,
        type: productInfo.value.type,
        logisticsMethod: logisticsList.value[e.form.activeLogistics].id,
        logisticsMethodName: logisticsList.value[e.form.activeLogistics].methodName,
        currency: areaInfo.value.currency,
        currencySymbol: areaInfo.value.currencySymbol,
        detailList: [],
        device: deviceType(),
        productId: pId.value,
        thaliId: e.thaliId || '',//套餐id，单品传空
        couponFlag: e.isPickup, //是否領取优惠券
        thaliName: e.thaliName,
        thaliPrice: e.thaliPrice
      }

      e.selectedProperty?.forEach(item => {

        let number = e.form.number || 1;
        let discountedPrice = skuInfo.value.length === 1 ? skuInfo.value[0].discountedPrice : item.discountedPrice;
        if (!discountedPrice) {
          discountedPrice = skuInfo.value.length === 1 ? skuInfo.value[0].price : item.price;
        }
        option.detailList.push({
          // productId: pId.value,
          productId: skuInfo.value.length === 1 ? skuInfo.value[0].productId : item.productId,
          productName: productInfo.value.titleExternal,
          currency: areaInfo.value.currency,
          currencySymbol: areaInfo.value.currencySymbol,
          propertyValueName: skuInfo.value.length === 1 ? skuInfo.value[0].name : item.name,
          propertyNameForeign: skuInfo.value.length === 1 ? skuInfo.value[0].propertyValueForeign : item.propertyValueForeign,
          propertyValueSku: skuInfo.value.length === 1 ? skuInfo.value[0].sku : item.sku,
          number: number,
          orderNumber: number,
          originalPrice: skuInfo.value.length === 1 ? skuInfo.value[0].price : item.price,
          discountedPrice: skuInfo.value.length === 1 ? skuInfo.value[0].discountedPrice : item.discountedPrice,
          totalPrice: discountedPrice * number,
        })
      })

      const order = await submitOrder(option)

      orderInfo.value = {orderId: order, ...option, ...e}
      showSuccess.value = true;
      message.success(getLanguage(productInfo.value.language).submitSuccess)
      e.success && e.success()

      //下单成功埋点
      // spmFaceBook({
      //   code: "Purchase",
      //   attachData: {
      //     value: e.priceInfo.discountPrice,
      //     currency: areaInfo.value.currency,
      //     content_type: 'product',
      //     content_ids: [pId.value],
      //     num_items: option.detailList.length,
      //     order_id: order.toString()
      //   }
      // }, productInfo.value)
    } catch (e) {

    } finally {
      isClick = false;
    }


  },
  top() {
    document.querySelector('.index')?.scrollTo(0, 0)
  },
  phone() {
    let dom = document.createElement('a');
    dom.href = `tel:${productInfo.value.phone}`
    dom.click();
  },
  email() {
    let dom = document.createElement('a');
    dom.href = `mailto:${productInfo.value.email}`
    dom.click();
  },
  whatsappContact() {
    let dom = document.createElement('a');
    dom.href = `whatsapp:${productInfo.value.whatsappContact}`
    dom.click();
  },
  lineContact() {
    window.open(productInfo.value.lineContact)
  },
  facebookContact() {
    window.open(productInfo.value.facebookContact)
  },
  messengerContact() {
    window.open(productInfo.value.messengerContact)
  },
  instagramContact() {
    window.open(`https://www.instagram.com/${productInfo.value.instagramContact}`)
  },
  logistics({method}) {
    getAreaList(method)
  },
  closeSuccess() {
    console.log('closeinde')
    showSuccess.value = false
  },
  closeOrder() {
    console.log('closeinde')
    showOrder.value = false
  }

}


onMounted(() => {
  initPage()

})
</script>
<style lang="scss">
.el-select-dropdown__wrap {
  max-height: 250PX;

  .el-select-dropdown__item {
    height: 30PX;
    display: flex;
    align-items: center;
    align-content: center;

    span {
      font-size: 10PX;
    }
  }
}

.el-collapse-item__header {
  font-size: 14PX;
  height: 47PX;
}
</style>
